package com.thinkTank.oa.service.impl;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.base.BaseServiceImpl;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.dao.DemandMapper;
import com.thinkTank.oa.dao.PersonMapper;
import com.thinkTank.oa.dao.ProjectMapper;
import com.thinkTank.oa.dao.ProjectOfPersonMapper;
import com.thinkTank.oa.entity.Demand;
import com.thinkTank.oa.entity.Person;
import com.thinkTank.oa.entity.Project;
import com.thinkTank.oa.entity.ProjectOfPerson;
import com.thinkTank.oa.service.PersonService;
import com.thinkTank.oa.util.FileUtils;
import com.thinkTank.oa.util.StrUtil;

/**
 * 专家serviceImpl
 * 
 * @author 董力 2018-8-9
 */
@Transactional
@Service("personService")
public class PersonServiceImpl extends BaseServiceImpl<Person> implements PersonService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProjectOfPersonMapper projectOfPersonMapper;
    @Autowired
    private DemandMapper demandMapper;
    
    
    private PersonMapper personMapper;

    @Autowired
    public void setPersonMapper(PersonMapper personMapper) {
        this.personMapper = personMapper;
        super.setBaseMapper(personMapper);
    }

    /**
     * 新增
     */
    public void addPerson(Person person) {
        personMapper.addPerson(person);
    }

    /**
     * 模糊查询专家表
     */
    public List<Person> findMPersonList(Person person) {
        return personMapper.findMPersonList(person);
    };

    /**
     * 通过pid查询专家
     * @param id
     * @return
     */
    public Person findPersonByPid(String pid) {
        return personMapper.findPersonByPid(pid);
    };

    /**
     * 通过姓名、电话、邮箱查询专家
     * @param person
     * @return
     */
    public Person findPersonByNameAndTellAndEmail(Person person) {
        return personMapper.findPersonByNameAndTellAndEmail(person);
    };

    /**
     * 修改
     * @param person
     */
    public void updatePerson(Person person) {
        personMapper.updatePerson(person);
    }

    @Override
    public void addHolder(Person person, Project project, MultipartFile file) {
//        String projectHolder = project.getProjectHolder();
        String personId = savePerson(person, file);
        
//        if (StringUtil.isEmpty(projectHolder))
//            projectHolder = person.getName();
//        else if (!projectHolder.contains(person.getName()))
//            projectHolder = projectHolder + "," + person.getName();
        
        //根据projectid和personid确定持有人是否已经存在
        List<ProjectOfPerson> popList = projectOfPersonMapper.queryByProjectId(project.getPid());
        if (popList.stream().map(ProjectOfPerson::getPersonId).noneMatch(person_id -> person_id.equals(personId))) {
            //根据projectid和personid确定持有人不存在后，保存到中间表以使project和person关联
            linkHolder(project.getPid(), personId);
        }
//        project.setProjectHolder(projectHolder);
//        projectMapper.updateProjectHolder(project);
    }

    /**
     * 通过ID直接关联project和person
     * @author pdz
     * @date 2018年10月18日
     * @param projectId
     * @param personId
     */
	public int linkHolder(String projectId, String personId) {
		ProjectOfPerson projectOfPerson = new ProjectOfPerson();
		projectOfPerson.setPid(StrUtil.getUUID32());
		projectOfPerson.setPersonId(personId);
		projectOfPerson.setProjectId(projectId);
		projectOfPerson.setRelationId(1);
		return projectOfPersonMapper.add(projectOfPerson);
	}

    /**
     * 根据姓名和任一联系方式判断，不存在才保存，否则不保存
     * @author pdz
     * @date 2018年9月11日
     * @param person
     * @param file 上传的附件
     * @return
     */
    private String savePerson(Person person, MultipartFile file) {
        List<Person> list = queryByContactAndName(person);
        // 在任一联系方式相同的情况下，名字相同就直接关联person表，否则先添加person再关联
//        Optional<Person> queryPerson = list.stream().filter(p -> p.getName().equals(person.getName())).findAny();
        String personId = !list.isEmpty() ? list.get(0).getPid() : person.getPid();
        if (list.isEmpty()) {
            //文件上传
            String fileName = FileUtils.transferTo(Constant.DEF_PERSON_PATH, file, "person");
            person.setAnnex(fileName);
            // 在person表添加数据
            add(person);
        } else {
        	//导入的时候用于返回专家ID
        	person.setExpertNumber(list.get(0).getExpertNumber());
        }
        return personId;
    }
    
    @Override
    public void updateHolder(Person person, MultipartFile file) {
        updatePerson(person, file);
        //名字不能有正则的元素，不然可能出问题
//        String holder = project.getProjectHolder().replaceFirst(oldHolderName, person.getName());
//        project.setProjectHolder(holder);
//        projectMapper.updateProjectHolder(project);
    }

    /**
     * 修改person，如果上传文件不为空则修改文件地址，否则不修改文件地址
     * @author pdz
     * @date 2018年8月27日
     * @param person
     * @param file
     */
    private void updatePerson(Person person, MultipartFile file) {
        String fileName = FileUtils.transferTo(Constant.DEF_PERSON_PATH, file, "person");
        //如果没有上传文件则不修改原文件地址
        Person per = checkContact(person);
        fileName = StringUtil.isEmpty(fileName) ? per.getAnnex() : fileName;
        person.setAnnex(fileName);
        personMapper.update(person);
    }

	private Person checkContact(Person person) {
		Person per = getById(person.getPid());
        //如果联系方式中包含*，则联系方式不变
        if (StringUtil.isNotEmpty(person.getFixedPhone()) && person.getFixedPhone().contains("*"))
        	person.setFixedPhone(per.getFixedPhone());
        if (StringUtil.isNotEmpty(person.getTell()) && person.getTell().contains("*"))
        	person.setTell(per.getTell());
        if (StringUtil.isNotEmpty(person.getEmail()) && person.getEmail().contains("*"))
        	person.setEmail(per.getEmail());
        if (StringUtil.isNotEmpty(person.getWechat()) && person.getWechat().contains("*"))
        	person.setWechat(per.getWechat());
        if (StringUtil.isNotEmpty(person.getOtherContact()) && person.getOtherContact().contains("*"))
        	person.setOtherContact(per.getOtherContact());
		return person;
	}

    @Override
    public void addContact(Person person, Project project, MultipartFile file) {
        String personId = savePerson(person, file);
        project.setProjectContactId(personId);
        projectMapper.updateProjectContact(project);
    }
    
    
    @Override
    public void update(@Valid Person person, MultipartFile file) {
        updatePerson(person, file);
    }

    public List<Person> queryByContactAndName(Person person) {
        return personMapper.queryByContact(person);
    };
    
    @Override
    public List<Person> queryByPersonIdList(List<String> personIdList) {
        return personMapper.queryByPersonIdList(personIdList);
    }
    
    @Override
    public List<Person> queryHolders(String projectId) {
        return personMapper.queryHolders(projectId);
    }
    
    @Override
    public void addContact(Person person, Demand demand, MultipartFile file) {
        String personId = savePerson(person, file);
        demand.setDemandContactId(personId);
        demandMapper.updateDemandContact(demand);
    }
    
    /**
     * 通过姓名+任意一种联系方式查询专家
     * @author dongli
     * @date 2018年9月5日
     * @param person
     * @return
     */
    public Person findPersonByInfo(Person person){
    	return personMapper.findPersonByInfo(person);
    }
    
    @Override
    public void importData(Person person) {
        savePerson(person, null);
    }
    
    public boolean updatePersonExists(Person person) {
    	Person person1 = checkContact(person);
    	List<Person> list = queryByContactAndName(person1);
    	return list != null && !list.isEmpty();
    }
    public List<Person> findPersonByIndex(Integer count){
    	return personMapper.findPersonByIndex(count);
    }
    
    @Override
    public List<Person> queryInExpertNumber(List<Integer> expertNumberList) {
    	return personMapper.queryInExpertNumber(expertNumberList);
    }
    
    /**
     * 模糊分页查询专家表
     * @author dongli
     * @date 2018年11月9日
     * @param person
     * @return
     */
    public List<Person> findMFPersonList(Person person){
    	return personMapper.findMFPersonList(person);
    }
}
